import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { EGUID, PrefabParser, UnityElement } from "../unity/PrefabParser.js";
import { UnityEngine } from "../typings/unity.js";
import { toolchain } from "../toolchain.js";

export class DisabledImageFinder {

    public async lookUp(): Promise<void> {
        const uiRoot = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources/ui');
        const prefabs = await fg('**/*.prefab', { cwd: uiRoot });

        let out = '';
        for (const p of prefabs) {
            const file = path.join(uiRoot, p);
            const pp = new PrefabParser();
            const prefab = await pp.parse(file);
            const usages: string[] = [];
            for (const e of prefab) {
                // console.log('check top element:', e.type, e.fileID);
                this.findDisabledImageInternal(e, '', usages);
            }

            if (usages.length > 0) {
                console.log(file);
                console.log('---------------');

                out += file + '\n';
                for (const u of usages) {
                    console.log(u);
                    out += u + '\n';
                }
                console.log('');
                out += '';
            }
        }

        await fs.writeFile(toolchain.opts.output!.replace('$', 'disabled'), out, 'utf-8');
    }

    private findDisabledImageInternal(element: UnityElement, path: string, usages: string[]): void {
        if (element.type == 'GameObject') {
            path += '.' + (element.object as UnityEngine.GameObject).m_Name;
            const image = element.components['MonoBehaviour_' + EGUID.Image];
            if (image != null) {
                if ((image.object as UnityEngine.MonoBehaviour).m_Enabled == 0 && (image.object as UnityEngine.UI.Image).m_Sprite.fileID.toString() != '0') {
                    usages.push(path);
                }
            }
            const rawImage = element.components['MonoBehaviour_' + EGUID.RawImage];
            if (rawImage != null) {
                if ((rawImage.object as UnityEngine.MonoBehaviour).m_Enabled == 0 && (rawImage.object as UnityEngine.UI.RawImage).m_Texture.fileID.toString() != '0') {
                    usages.push(path);
                }
            }
            if (element.children != null) {
                for (const c of element.children) {
                    this.findDisabledImageInternal(c, path, usages);
                }
            }
        }
    }
}
